package main;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.mail.Multipart;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

import com.sun.xml.internal.stream.Entity.ExternalEntity;
import com.oreilly.servlet.MultipartRequest;

import DBClasses.Game;
import DBClasses.GameComment;
import DBClasses.GameType;
import DBClasses.NewsLetter;
import DBClasses.User;

@SuppressWarnings("serial")
public class AddToBasket extends BaseServlet
{
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		String game_id_str = req.getParameter("id");
		if (game_id_str != null && !game_id_str.equals(""))
		{
			long game_id = 0L;
			try
			{
				game_id = Long.parseLong(game_id_str);
			} catch (Exception ex)
			{
				resp.getWriter().write("fail");
			}
			if (game_id > 0)
			{
				PersistenceManager manager = PMF.get().getPersistenceManager();
				List<Game> gs = (List<Game>) manager.newQuery(
						"select from " + Game.class.getName() + " where id == "
								+ game_id).execute();
				if (gs != null && gs.size() > 0)
				{
					Basket bskt = (Basket) req.getSession().getAttribute(
							"basket");
					if (bskt == null || bskt.UserBasket.size() <= 0)
					{
						bskt=new Basket();
						req.getSession().setAttribute("basket", bskt);
					}
					Item item=bskt.Contains(gs.get(0));
					if(item!=null)
					{
						item.Count++;
					}else
					{
						Item new_itm=new Item(gs.get(0));
						bskt.UserBasket.add(new_itm);
					}
					resp.getWriter().write("success");
				} else
					resp.getWriter().write("fail");
				manager.close();
			}
		} else
			resp.getWriter().write("fail");
	}
}
